import Vue from 'vue'
import VueRouter from 'vue-router'
import home from '../views/home/index.vue'
import qa from '../views/qa/index.vue'
import movie from '../views/movie/index.vue'
import user from '../views/user/index.vue'
import login from '../views/user/login.vue'
import student from '../views/user/student.vue'
import edit from '../views/user/edit.vue'
import notfound from '../views/notfound/index.vue'
import { getToken } from '../utils/token'
Vue.use(VueRouter)

const routes = [
  {
    name: 'home',
    path: '/home',
    component: home,
    meta: { showTab: true }
  },
  {
    name: 'login',
    path: '/login',
    component: login
  },
  {
    name: 'movie',
    path: '/movie',
    component: movie,
    meta: { showTab: true }
  },
  {
    name: 'qa',
    path: '/qa',
    component: qa,
    meta: { showTab: true }
  },
  {
    name: 'user',
    path: '/user',
    component: user,
    meta: { showTab: true, needLogin: true }
  },
  {
    name: 'notfound',
    path: '/notfound',
    component: notfound
  },

  {
    name: 'edit',
    path: '/edit',
    component: edit,
    meta: { needLogin: true }
  },
  {
    name: 'student',
    path: '/student',
    component: student
  },

  // 重定向
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '*',
    redirect: '/notfound'
  }
]
// --------------------------------------------------------
/* 去掉路由跳转reject异常提示
注意：我们是直接修改VueRouter的原型，所以需要在实例化之前调用
*/
// (1)先保存路由原型链中默认的跳转函数
const originalPush = VueRouter.prototype.push
// (2)替换原型链中的push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) {
    // 正常执行
    // originalPush.call() : 我们自定义的push底层还是调用默认的push
    return originalPush.call(this, location, onResolve, onReject)
  }
  // 如果有异常，本来这个err默认是抛出的，我们直接不做任何处理（给吞掉了）
  /*
  底层默认是抛出异常：err => {throw err}
  我们不抛出，不做任何处理：err => err
  */
  return originalPush.call(this, location).catch(err => err)
}
// ----------------------------------------------------------
const router = new VueRouter({
  routes
})
// 导航守卫
router.beforeEach((to, from, next) => {
  // console.log('to:', to)
  // console.log('from:', from)
  // 判断meta里是否有needLogin，token是否有
  // token过期的时候怎么办？？？？？
  // 这里是不是用用户信息判断更好？
  if (to.meta.needLogin && !getToken()) {
    // 如果需要登录，并且没有token，则跳转到登录页面
    next({ path: '/login' })
  } else {
    // 否则正常跳转
    next()
  }

  next()
})
export default router
